package com.cdy.demo.agent;

import javassist.ClassPool;
import javassist.CtClass;

import java.io.File;
import java.io.FileOutputStream;

import static com.cdy.demo.agent.Agent.commandLineContext;


public class ClassFileCommand implements Command {

    @Override
    public boolean meet() {
        return commandLineContext.getCommandType().equals("classfile") ||
                commandLineContext.getCommandType().equals("all");
    }

    @Override
    public byte[] transform(CommandContext context)  {
        String className = context.getClassName();
        String clazz = commandLineContext.getCommandClass();
        if (className.equals(clazz)) {
            try {
                ClassPool classPool = ClassPool.getDefault();
                CtClass ctclass = classPool.get(clazz);
                String path = clazz.replace(".", "/");
                byte[] byteArr = ctclass.toBytecode();
                File file = new File("/Users/chendongyi/Downloads/ideaProjects/demo_maven/target/"+path+".class");
                if (file.exists()) {
                    file.delete();
                }
                FileOutputStream fos = new FileOutputStream(file);
                fos.write(byteArr);
                fos.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return context.getClassfileBuffer();
    }
}
